package easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import easyexcel.entity.Hospital;
import easyexcel.mapper.HospitalMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @description:easyexcel导入监听器
 * @author: jichao
 * @date: 2021/4/28 10:11
 */
@Component
public class HospitalListener extends AnalysisEventListener<Hospital> {

    private static final Logger LOGGER = LoggerFactory.getLogger(HospitalListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;
    List<Hospital> list = new ArrayList();

    private HospitalMapper hospitalMapper;

    public HospitalListener(HospitalMapper hospitalMapper) {
        this.hospitalMapper = hospitalMapper;
    }


    @Override
    public void invoke(Hospital hospital, AnalysisContext analysisContext) {
        System.out.println("invoke方法被调用");
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(hospital));
        System.err.println(hospital);
        hospital.setId(HospitalListener.generate());
        hospital.setCreatedDate(new Date());
        hospital.setLastModifiedDate(new Date());
        hospital.setRxOpen(true);
        System.err.println(hospital);
        list.add(hospital);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            System.err.println(list.size());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("doAfterAllAnalysed方法 被调用");
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        hospitalMapper.insertHospital(list);
        // 存储完成清理 list
        list.clear();
        LOGGER.info("存储数据库成功！");
    }

    public static String generate() {
        UUID uuid = UUID.randomUUID();
        byte[] uuidArr = asByteArray(uuid);
        String s = new BASE64Encoder().encode(uuidArr);
        return s.replace("=", "").replace("/", "_").replace("+", "-");
    }

    private static byte[] asByteArray(UUID uuid) {
        long msb = uuid.getMostSignificantBits();
        long lsb = uuid.getLeastSignificantBits();
        byte[] buffer = new byte[16];


        for (int i = 0; i < 8; i++) {
            buffer[i] = (byte) (msb >>> 8 * (7 - i));
        }
        for (int i = 8; i < 16; i++) {
            buffer[i] = (byte) (lsb >>> 8 * (7 - i));
        }
        return buffer;
    }
}
